﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using QLHREntities;
namespace QLHuongRungDAO
{
    public class NguyenLieuDAO
    {
        private QLHuongRungEntities db = new QLHuongRungEntities();
        public NguyenLieuDAO() { }
        public QLHREntities.NguyenLieu LayNguyenLieu(int MaNguyenLieu)
        {
            NguyenLieu nl = (from nguyenlieu in db.NguyenLieux
                             where nguyenlieu.MaNL == MaNguyenLieu
                             select nguyenlieu).First();
            return nl;
        }

        public void CapNhatKho(NguyenLieu nl)
        {
            db.Entry(nl).State = System.Data.EntityState.Modified;
            db.SaveChanges();
        }
        public List<NguyenLieuDatHang> LayDanhSachNguyenLieu(int maThucDon)
        {
            var query = from cttd in db.ChiTietThucDons
                        where cttd.ThucDon == maThucDon
                        && cttd.MonAn != null
                        && cttd.NguyenLieu != null
                        join ma in db.NguyenLieux on cttd.NguyenLieu equals ma.MaNL
                        join soluong in db.ChiTietMonAns on new { MaMA = cttd.MonAn.Value, MaNL = cttd.NguyenLieu.Value } equals new { MaMA = soluong.MonAn, MaNL = soluong.NguyenLieu }
                        join monan in db.MonAns on cttd.MonAn equals monan.MaMonAn
                        //  group ma by ma.MaNL into g
                        select new { TenNguyenLieu = ma.TenNguyenLieu, MaNL = ma.MaNL, TenMonAn = monan.TenMonAn, SoLuong = soluong.SoLuong.Value, SoLuongTon = ma.SoLuongTon.Value, SoLuongTonToiThieu = ma.SoLuongTonToiThieu.Value, NhaCungCap = ma.NhaCungCap.Value, MaCTTD = cttd.MaCTTD, Gia = ma.DonGia.Value }; //g.Select(ma => ma.TenNguyenLieu), MaNL = g.Key};
            //   List<NguyenLieu> result = new List<NguyenLieu>();
            List<NguyenLieuDatHang> result = new List<NguyenLieuDatHang>();
            foreach (var item in query.ToList())
            {
                NguyenLieuDatHang ma = new NguyenLieuDatHang();
                ma.TenNguyenLieu = item.TenNguyenLieu;
                ma.MaNL = item.MaNL;
                ma.TenMonAn = item.TenMonAn;
                ma.SoLuongTon = item.SoLuongTon;
                ma.SoLuongTonToiThieu = item.SoLuongTonToiThieu;
                ma.SoLuongCan = item.SoLuong;
                ma.NhaCungCap = item.NhaCungCap;
                ma.ChiTietThucDon = item.MaCTTD;
                ma.Gia = item.Gia;
                result.Add(ma);
            }
            return result;
        }
    }
}
